using CSharpX;
using UnityEngine;

namespace UnityX
{
    public class AnimationBehaviour : MonoBehaviour
    {
        public float delay = 0f;
        public float duration = 0.4f;
        [Range(0, 1)]
        public float curve = 0.8f;

        private bool m_Playing = false;
        private float m_LastFrameTime;
        private float m_ElapsedTime;
        protected void OnEnable()
        {
            Play();
        }
        protected void OnDisable()
        {
            if (!m_Playing) return;
            m_Playing = false;
            End();
        }
        public void Play()
        {
            m_LastFrameTime = Time.time;
            m_ElapsedTime = 0f - delay;
            m_Playing = true;
            Begin();
        }
        protected void Update()
        {
            if (!m_Playing) return;

            float deltaTime = Time.time - m_LastFrameTime;
            m_LastFrameTime = Time.time;
            if (deltaTime < 0.16f)
            {
                m_ElapsedTime += deltaTime;
            }
            else
            {
                m_ElapsedTime += 0.016f;
            }
            if (m_ElapsedTime < duration)
            {
                Set(Curve.X3(curve, m_ElapsedTime / duration));
            }
            else
            {
                m_Playing = false;
                End();
            }
        }

        protected virtual void Begin()
        {

        }
        protected virtual void Set(float t)
        {

        }
        protected virtual void End()
        {

        }
    }
}